import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_xupdate/flutter_xupdate.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:r_upgrade/r_upgrade.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/common/model/app_upgrade_resp.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/toast_utils.dart';

class UpgradeUtils {
  static bool isCheckUpdate = false;

  /// 初始化XUpdate升级插件
  static Future<void> initXUpdate() async {
    if (Platform.isAndroid) {
      PackageInfo packageInfo = await PackageInfo.fromPlatform();
      final upgradeParams = {
        'platform': 'android',
        'versionNum': packageInfo.buildNumber,
      };
      FlutterXUpdate.init(

              ///是否输出日志
              debug: true,

              ///是否使用post请求
              isPost: false,

              ///post请求是否是上传json
              isPostJson: true,

              ///是否开启自动模式
              isWifiOnly: false,

              ///是否开启自动模式
              isAutoMode: false,

              ///需要设置的公共参数
              supportSilentInstall: false,

              ///在下载过程中，如果点击了取消的话，是否弹出切换下载方式的重试提示弹窗
              enableRetry: false,
              params: upgradeParams)
          .then((value) {
        XLogger.info("初始化成功: $value");
      }).catchError((error) {
        XLogger.error(error);
      });

      FlutterXUpdate.setErrorHandler(onUpdateError: (Map<String, dynamic>? message) async {
        XLogger.error("出错了: $message");
      });

      FlutterXUpdate.setCustomParseHandler(onUpdateParse: (String? json) async {
        XLogger.info("解析json: $json");
        return customParseJson(json!);
      });
    } else {}
  }

  ///将自定义的json内容解析为UpdateEntity实体类
  static UpdateEntity customParseJson(String json) {
    AppUpgradeResp appUpgradeResp = AppUpgradeResp().fromJsonStr(json);
    AppUpgradeData appInfo = appUpgradeResp.data!;
    return UpdateEntity(
        hasUpdate: appInfo.updated,
        isForce: appInfo.forceUpdate == '1',
        versionCode: appInfo.versionNum,
        versionName: appInfo.appVersion,
        updateContent: appInfo.upgradeInfo,
        downloadUrl: appInfo.downloadUrl,
        apkSize: appInfo.apkSize);
  }

  static UpdateEntity customParseJsonByAppUpgradeData(AppUpgradeData upgradeData) {
    return UpdateEntity(
      hasUpdate: upgradeData.updated,
      isForce: upgradeData.forceUpdate == '1',
      versionCode: upgradeData.versionNum,
      versionName: upgradeData.appVersion,
      updateContent: upgradeData.upgradeInfo,
      downloadUrl: upgradeData.downloadUrl,
    );
  }

  /// 检查更新
  static void checkUpdate(context, {String fromPage = ''}) async {
    if (isCheckUpdate) {
      return;
    }
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    final upgradeParams = {
      'platform': Platform.isAndroid ? 'android' : 'ios',
      'versionNum': packageInfo.buildNumber,
      'fromPage': fromPage,
    };
    ToastUtils.showToast('该功能未实现');
    // final res = await post<AppUpgradeResp, AppUpgradeResp>('', data: upgradeParams, decodeType: AppUpgradeResp());
    final res = await get<AppUpgradeResp, AppUpgradeResp>('https://ljwl.tech/app/version',decodeType: AppUpgradeResp());
    XLogger.info(res);

    res.when(
        success: (AppUpgradeResp resp) {
          XLogger.info(resp);
          if (resp.code == 200) {
            XLogger.info('检查更新：${resp.data}');
            if (resp.data?.updated == true) {
              // 判断平台
              if (Platform.isAndroid) {
                FlutterXUpdate.updateByInfo(
                  updateEntity: customParseJsonByAppUpgradeData(resp.data!),
                  // themeColor: '#FF165DFF',
                );
              } else {
                // iOS
                showIOSUpdateDialog(resp.data!, context);
              }
            }
          } else {}
          isCheckUpdate = true;
        },
        failure: (String msg, int code) {
          XLogger.info(msg);

        });
  }

  /// 主动调用检查更新
  static void checkUpdateByManual(BuildContext context, {String fromPage = ''}) async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    final upgradeParams = {
      'platform': Platform.isAndroid ? 'android' : 'ios',
      'versionNum': packageInfo.buildNumber,
      'fromPage': fromPage,
    };
    ToastUtils.showToast('该功能未实现');
    final res = await post<AppUpgradeResp, AppUpgradeResp>('', data: upgradeParams, decodeType: AppUpgradeResp());
    res.when(
        success: (AppUpgradeResp resp) {
          if (resp.code == 200) {
            XLogger.info('检查更新：${resp.data}');
            if (resp.data?.updated == true) {
              // 判断平台
              if (Platform.isAndroid) {
                FlutterXUpdate.updateByInfo(
                  updateEntity: customParseJsonByAppUpgradeData(resp.data!),
                  // themeColor: '#FF165DFF',
                );
              } else {
                // iOS
                showIOSUpdateDialog(resp.data!, context);
              }
            } else {
              ToastUtils.showToast('已是最新版本');
            }
          } else {}
        },
        failure: (String msg, int code) {});
  }

  /// 显示iOS更新弹窗
  static void showIOSUpdateDialog(AppUpgradeData upgradeData, BuildContext context) {
    var isForceUpdate = upgradeData.forceUpdate == '1';
    showCupertinoDialog(
      context: context,
      builder: (context) {
        return CupertinoAlertDialog(
          title: Text(upgradeData.upgradeTitle ?? '发现新版本'),
          content: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('是否更新到${upgradeData.appVersion}版本?',
                  textAlign: TextAlign.left,
                  style: TextStyle(
                    color: AppTheme.themeConfig.primaryTextColor,
                    fontSize: 16,
                  )),
              const SizedBox(
                height: 12,
              ),
              Text('${upgradeData.upgradeInfo}',
                  // 居左显示
                  textAlign: TextAlign.left,
                  style: TextStyle(
                    color: AppTheme.themeConfig.primaryTextColor,
                    fontSize: 14,
                  )),
            ],
          ),
          actions: [
            if (!isForceUpdate)
              CupertinoDialogAction(
                child: const Text('取消'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            CupertinoDialogAction(
              child: const Text('去更新'),
              onPressed: () {
                if (!isForceUpdate) {
                  // 强制更新，不允许取消
                  Navigator.of(context).pop();
                }
                // 跳转到AppStore
                RUpgrade.upgradeFromAppStore(upgradeData.downloadUrl!);
              },
            ),
          ],
        );
      },
    );
  }
}
